//
//  NoticeCenterViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/5/8.
//

import UIKit

class NoticeCenterViewController: CommonViewController {
    fileprivate var scrollChange:(()->Void)?
    fileprivate var vcs:Array<NoticeTableViewController?> = []
    fileprivate var menuItems:Array<TabsModel> = []
    fileprivate var currentIndex = 0
    fileprivate var beforeIndex = 0
    fileprivate let setitem = UIBarButtonItem.init(title: "设置", style:.plain , target: self, action: #selector(setting))

    @objc func setting(){
        self.pushViewController(MessageSetViewController(), animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "消息通知"
        // SetButton
        
        setitem.tintColor = B000_COLOR
        setitem.target = self
        
        self.navigationItem.rightBarButtonItem = DataManager.login ? setitem : nil
        
        menuItems = [TabsModel.init(name: "全部", id: 1),
                    TabsModel.init(name: "系统通知", id: 21),
                    TabsModel.init(name: "评论", id: 21),
                    TabsModel.init(name: "粉丝", id: 21),
                    TabsModel.init(name: "点赞", id: 21),
                    TabsModel.init(name: "@我", id: 21)]
        let tabs = TabsView(items: menuItems)
        view.addSubview(tabs)
        tabs.snp.makeConstraints({
            $0.left.right.equalTo(0)
            $0.height.equalTo(35)
            if #available(iOS 11.0, *) {
                $0.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            } else {
                // Fallback on earlier versions
                $0.top.equalTo(0)
            }
        })
        
        let pageController = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        
        tabs.valueChanged = { [weak self]item in
            let index = self?.menuItems.firstIndex(where: { (arr) -> Bool in
                return arr.name == item.0
            })
            guard index != self?.currentIndex else {
                return
            }
            self?.currentIndex = index!
            self?.updateViewControllers()
            let vc = self?.vcs[index!]
            pageController.setViewControllers([vc!], direction: .forward, animated: false) { (res) in
                SystemLog("setViewControllers|\(res)")
            }
        }
        
        self.scrollChange = {[weak self] in
            tabs.nextTab(self!.currentIndex)
        }
        
        let w = UIScreen.main.bounds.width
        self.vcs = Array<NoticeTableViewController?>(repeating: nil, count: menuItems.count)
        self.updateViewControllers()
        pageController.dataSource = self
        pageController.delegate = self
        self.addChild(pageController)
        self.view.addSubview(pageController.view)
        pageController.view.snp.makeConstraints({
            $0.top.equalTo(tabs.snp.bottom)
            if #available(iOS 11.0, *) {
                $0.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            } else {
                // Fallback on earlier versions
                $0.bottom.equalTo(0)
            }
            $0.left.equalTo(0)
            $0.width.equalTo(w)
        })
        pageController.setViewControllers([vcs[0]!], direction: .reverse, animated: false) { (res) in
            SystemLog("setViewControllers|\(res)")
        }
        NotificationMananger.addNotification(.LoginCompletion, target: self, selector: #selector(loginSuccess))
        
    }
    @objc func loginSuccess(){
        self.navigationItem.rightBarButtonItem = DataManager.login ? setitem : nil
    }
    func updateViewControllers() {
        for i in 0..<vcs.count {
            if i>self.currentIndex+1 || i<self.currentIndex-1 {
                vcs[i] = nil
            }else{
                if vcs[i] == nil {
                    let vc = NoticeTableViewController()
                    vcs[i] = vc
                }
                vcs[i]?.reloadData(text: menuItems[i].name)
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }
    override func viewDidDisappear(_ animated: Bool) {
        NotificationMananger.removeAllNotifocation(self)
    }
}
extension NoticeCenterViewController:UIPageViewControllerDelegate{
    func presentationCount(for pageViewController: UIPageViewController) -> Int {
        return vcs.count
    }
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if finished && completed {
            // 滑动完成tabbars变动
            self.updateViewControllers()
            self.scrollChange!()
        }
    }
    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        // 获取当前页码
        self.currentIndex = self.vcs.firstIndex(of: pendingViewControllers[0] as? NoticeTableViewController)!
    }
}
extension NoticeCenterViewController:UIPageViewControllerDataSource{
    func nextViewController(_ viewController:UIViewController,isAfter:Bool) -> UIViewController? {
        guard DataManager.login == true else {
            return nil
        }
        guard var index = vcs.firstIndex(of: viewController as? NoticeTableViewController) else {
            return nil
        }
        if(isAfter){
            index += 1
        }else{
            index -= 1
        }
        
        if index < 0 || index == vcs.count{
            return nil
        }
        self.scrollChange!()
        SystemLog(index)
        return vcs[index]
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        return nextViewController(viewController, isAfter: false)
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        return nextViewController(viewController, isAfter: true)
    }

}
